package com.jia.lidao.ui.personal.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.jia.lidao.App;
import com.jia.lidao.Constans;
import com.jia.lidao.R;
import com.jia.lidao.UserUtils;
import com.jia.lidao.enity.OrderInfo;
import com.jia.lidao.enity.PayResponseDTO;
import com.jia.lidao.enity.RefreshStatusMessage;
import com.jia.lidao.enity.WXpayEnity;
import com.jia.lidao.network.http.BusinessManager;
import com.jia.lidao.network.http.MyCallback;
import com.jia.lidao.network.http.request.impl.DealWithOrderRequest;
import com.jia.lidao.network.http.request.impl.PayRequest;
import com.jia.lidao.network.http.request.impl.ReceptConfirmRequest;
import com.jia.lidao.network.http.request.impl.RemindDeliveryRequest;
import com.jia.lidao.network.http.request.impl.RemindPayRequest;
import com.jia.lidao.network.http.request.impl.RemindReceptRequest;
import com.jia.lidao.others.ui.AppraiseActivity;
import com.jia.lidao.others.ui.fragment.OrderDetailActivity;
import com.jia.lidao.others.utils.DisplayUtil;
import com.jia.lidao.ui.BaseActivity;
import com.jia.lidao.ui.order.AuditActivity;
import com.jia.lidao.ui.order.ConfirmOrderActivity;
import com.jia.lidao.ui.order.TransportActivity;
import com.jia.lidao.utils.ImgLoaderUtil;
import com.jia.lidao.utils.ListUtil;
import com.jia.lidao.utils.LogUtil;
import com.jia.lidao.widget.ListView4ScrollView;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.unionpay.UPPayAssistEx;

import org.greenrobot.eventbus.EventBus;
import org.w3c.dom.Text;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by jia on 17/12/16.
 */

public class OrderListAdapter extends BaseAdapter {

    private Activity context;
    private OrderDetailAdapter adapter;

    private List<OrderInfo> mDatas;

    private int role;

    private IWXAPI iwxapi;

    public OrderListAdapter(Activity context, int role) {
        this.context = context;
        mDatas = new ArrayList<>();
        this.role = role;
        iwxapi = WXAPIFactory.createWXAPI(context.getApplicationContext(), Constans.APP_ID);
        // 将该app注册到微信
        iwxapi.registerApp(Constans.APP_ID);
    }

    @Override
    public int getCount() {
        return mDatas.size();
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder = null;
        if (view == null) {
            viewHolder = new ViewHolder();
            view = LayoutInflater.from(context).inflate(R.layout.item_orderlist, null);
            viewHolder.mechantthumb = (ImageView) view.findViewById(R.id.shop_icon_img);
            viewHolder.listView4ScrollView = (ListView4ScrollView) view.findViewById(R.id.orderdeataillist);
            viewHolder.createTimeTxt = (TextView) view.findViewById(R.id.order_time_tv);
            viewHolder.mechantnametxt = (TextView) view.findViewById(R.id.shop_name_tv);
            viewHolder.orderstatusTxt = (TextView) view.findViewById(R.id.order_status_tv);
            viewHolder.totalsizeTxt = (TextView) view.findViewById(R.id.order_totalnum_tv);
            viewHolder.totalPriceTxt = (TextView) view.findViewById(R.id.order_totalprice_tv);
            viewHolder.dealTxt = (TextView) view.findViewById(R.id.order_status_manage_tv);
            viewHolder.dealLL = (RelativeLayout) view.findViewById(R.id.order_manager_rl);
            viewHolder.orderSnTxt = (TextView) view.findViewById(R.id.ordersnTv);
            viewHolder.merchantLl = (LinearLayout) view.findViewById(R.id.mechantLL);
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }
        if (mDatas.get(i).merchant != null) {
            ImgLoaderUtil.displayImage(mDatas.get(i).merchant.thumb.replace("https://", "http://"), viewHolder.mechantthumb);
            viewHolder.mechantnametxt.setText(mDatas.get(i).merchant.name);
        }
        viewHolder.orderstatusTxt.setText(mDatas.get(i).status_name);
        viewHolder.createTimeTxt.setText(mDatas.get(i).created_time);
        if (mDatas.get(i).goods_count == 0) {
            int n = 0;
            for (int j = 0; j < mDatas.get(i).order_goods.size(); j++) {
                n += mDatas.get(i).order_goods.get(j).quantity;
            }
            viewHolder.totalsizeTxt.setText("共 " + n + " 件商品");
        } else {
            viewHolder.totalsizeTxt.setText("共 " + mDatas.get(i).goods_count + " 件商品");
        }
        viewHolder.totalPriceTxt.setText("¥" + DisplayUtil.double2String(mDatas.get(i).pay_money));
        viewHolder.listView4ScrollView.setClickable(false);
        viewHolder.listView4ScrollView.setEnabled(false);
        adapter = new OrderDetailAdapter(context, mDatas.get(i).order_goods);


        //status：-2已关闭 -1已驳回 1待付款 2待审核 3待发货 4待收货 5待评价 6已完成 ,
        if (role == Constans.ORDERSEND) {
            viewHolder.merchantLl.setVisibility(View.VISIBLE);
            viewHolder.orderSnTxt.setVisibility(View.GONE);
            if (mDatas.get(i).status == 1) {
                viewHolder.dealLL.setVisibility(View.VISIBLE);
                viewHolder.dealTxt.setText("提醒付款");
            } else if (mDatas.get(i).status == 2) {
                viewHolder.dealLL.setVisibility(View.VISIBLE);
                viewHolder.dealTxt.setText("去审核");
            } else if (mDatas.get(i).status == 3) {
                viewHolder.dealLL.setVisibility(View.VISIBLE);
                viewHolder.dealTxt.setText("去发货");
            } else if (mDatas.get(i).status == 4) {
                viewHolder.dealLL.setVisibility(View.VISIBLE);
                viewHolder.dealTxt.setText("提醒收货");
            } else {
                viewHolder.dealLL.setVisibility(View.GONE);
            }
        } else if (role == Constans.ORDERRECEIVE) {
            viewHolder.merchantLl.setVisibility(View.GONE);
            viewHolder.orderSnTxt.setVisibility(View.VISIBLE);
            viewHolder.orderSnTxt.setText("订单编号: " + mDatas.get(i).order_sn);
            if (mDatas.get(i).status == 1) {
                viewHolder.dealLL.setVisibility(View.VISIBLE);
                viewHolder.dealTxt.setText("立即付款");
            } else if (mDatas.get(i).status == 2) {
                viewHolder.dealLL.setVisibility(View.GONE);
//                viewHolder.dealTxt.setText("去发货");
            } else if (mDatas.get(i).status == 3) {
                viewHolder.dealLL.setVisibility(View.VISIBLE);
                viewHolder.dealTxt.setText("提醒发货");
            } else if (mDatas.get(i).status == 4) {
                viewHolder.dealLL.setVisibility(View.VISIBLE);
                viewHolder.dealTxt.setText("确认收货");
            } else if (mDatas.get(i).status == 5) {
                viewHolder.dealLL.setVisibility(View.VISIBLE);
                viewHolder.dealTxt.setText("去评价");
            } else {
                viewHolder.dealLL.setVisibility(View.GONE);
            }
        }
        viewHolder.dealTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (context instanceof BaseActivity) {
                    ((BaseActivity) context).showDialog("");
                }
                if (role == Constans.ORDERRECEIVE) {
                    if (mDatas.get(i).status == 3 || mDatas.get(i).status == 4) {
                        dealWithOrder(role, mDatas.get(i).status, mDatas.get(i).id);
                    } else if (mDatas.get(i).status == 5) {
                        ((BaseActivity) context).dismissDialog();
                        context.startActivity(new Intent(context, AppraiseActivity.class).putExtra("ID", mDatas.get(i).id));
                    } else if (mDatas.get(i).status == 1) {
                        BusinessManager.getInstance().payOrder(new PayRequest(mDatas.get(i).id), new MyCallback<PayResponseDTO>() {
                            @Override
                            public void onSuccess(PayResponseDTO result, String message) {
                                ((BaseActivity) context).dismissDialog();
                                if (result == null)
                                    if (context instanceof BaseActivity) {
                                        ((BaseActivity) context).showToast("获取支付信息失败");
                                        return;
                                    }
                                switch (mDatas.get(i).payment_type) {
                                    case 1:
                                        doZFBzf(result.alipay);
                                        break;
                                    case 2:
                                        wxPay(result.wechat);
                                        break;
                                    case 3:
                                        dpUPPay(result.unionpay);
                                        break;
                                }
                            }

                            @Override
                            public void onError(String errorCode, String message) {
                                if (context instanceof BaseActivity) {
                                    ((BaseActivity) context).showToast(message);
                                    ((BaseActivity) context).dismissDialog();
                                }
                            }

                            @Override
                            public void onFinished() {

                            }

                            @Override
                            public void onRefreshToken() {
                                UserUtils.getInstance().goToLogin(context);
                            }
                        });
                    }
                } else if (role == Constans.ORDERSEND) {
                    if (mDatas.get(i).status == 1 || mDatas.get(i).status == 4) {
                        dealWithOrder(role, mDatas.get(i).status, mDatas.get(i).id);
                    } else if (mDatas.get(i).status == 3) {
                        ((BaseActivity) context).dismissDialog();
                        context.startActivity(new Intent(context, TransportActivity.class).putExtra("ID", mDatas.get(i).id));
                    } else if (mDatas.get(i).status == 2) {
                        context.startActivity(new Intent(context, AuditActivity.class).putExtra("ID", mDatas.get(i).id).putExtra("paymenttype", mDatas.get(i).payment_type).putExtra("status",mDatas.get(i).status).putExtra("role",role));
                    }
                }
                ((BaseActivity) context).dismissDialog();
            }
        });
        viewHolder.listView4ScrollView.setAdapter(adapter);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                context.startActivity(new Intent(context, ConfirmOrderActivity.class).putExtra("ID", mDatas.get(i).id).putExtra("role", role));
            }
        });
        return view;
    }

    class ViewHolder {
        ListView4ScrollView listView4ScrollView;

        ImageView mechantthumb;

        TextView mechantnametxt;

        TextView orderstatusTxt;

        TextView createTimeTxt;

        TextView totalsizeTxt;

        TextView totalPriceTxt;

        RelativeLayout dealLL;

        TextView dealTxt;

        TextView orderSnTxt;

        LinearLayout merchantLl;
    }


    /**
     * 刷新列表
     *
     * @param datas
     */
    public void refreshUi(List<OrderInfo> datas) {
        mDatas.clear();
        if (!ListUtil.isEmpty(datas)) {
            mDatas.addAll(datas);
        }
        notifyDataSetChanged();
    }

    /**
     * 刷新列表
     *
     * @param datas
     */
    public void refreshUiByAdd(List<OrderInfo> datas) {
        if (!ListUtil.isEmpty(datas)) {
            mDatas.addAll(datas);
        }
        notifyDataSetChanged();
    }


    private void dealWithOrder(final int role, final int status, int id) {
        BusinessManager.getInstance().dealWithOrder(new DealWithOrderRequest(role, status, id), new MyCallback<Void>() {
            @Override
            public void onSuccess(Void result, String message) {
                if (context instanceof BaseActivity) {
                    if (role == Constans.ORDERRECEIVE) {
                        switch (status) {
                            case 3:
                                ((BaseActivity) context).showToast("提醒发货成功");
                                break;
                            case 4:
                                ((BaseActivity) context).showToast("确认收货成功");
                                break;
                            case 7:
                                ((BaseActivity) context).showToast("取消订单成功");
                                break;
                            case 8:
                                ((BaseActivity) context).showToast("删除订单成功");
                                break;
                            default:
                                ((BaseActivity) context).showToast(message);
                                break;
                        }
                    } else {
                        switch (status) {
                            case 1:
                                ((BaseActivity) context).showToast("提醒付款成功");
                                break;
                            case 4:
                                ((BaseActivity) context).showToast("提醒收货成功");
                                break;
                            default:
                                ((BaseActivity) context).showToast(message);
                                break;

                        }
                    }

                    if (role == Constans.ORDERRECEIVE) {
                        if (status == 4) {
                            EventBus.getDefault().post(new RefreshStatusMessage());
                        }
                    }
                    ((BaseActivity) context).dismissDialog();
                }
            }

            @Override
            public void onError(String errorCode, String message) {
                if (context instanceof BaseActivity) {
                    ((BaseActivity) context).showToast(message);
                    ((BaseActivity) context).dismissDialog();
                }
            }

            @Override
            public void onFinished() {

            }

            @Override
            public void onRefreshToken() {
                UserUtils.getInstance().goToLogin(context);
            }
        });
    }


    private void doZFBzf(final String orderSN) {

        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(
                        context);
                final Map<String, String> result = alipay
                        .payV2(orderSN, true);
                Log.i("msp", result.toString());
                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!TextUtils.isEmpty(result.get("memo"))) {
                            Toast.makeText(context, result.get("memo"), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private void wxPay(WXpayEnity wXpayResult) {
        PayReq request = new PayReq();
        request.appId = wXpayResult.appid;
        request.partnerId = wXpayResult.partnerid;
        request.prepayId = wXpayResult.prepayid;
        request.packageValue = "Sign=WXPay";
        request.nonceStr = wXpayResult.noncestr;
        request.timeStamp = wXpayResult.timestamp;
        request.sign = wXpayResult.sign;
        iwxapi.sendReq(request);
    }

    private void dpUPPay(String tn) {
        UPPayAssistEx.startPay(context, null, null, tn, "01");
    }


}
